const { verify } = require("jsonwebtoken");
const {
  USER_TOKEN_SECRET_KEY,
  JWT_WHITE_LIST,
  TOKEN_ISSUE_KEY,
} = require("../../sys_config");

module.exports = {
  name: "jwt",

  async core(ctx, next) {
    if (JWT_WHITE_LIST.includes(ctx.path)) {
      //在白名单中不用验证 直接下一步
      await next();
    } else {
      const token = ctx.request.headers[TOKEN_ISSUE_KEY.toLocaleLowerCase()];
      if (!token) {
        rsp_no_auth("请先登陆");
      } else {
        try {
          verify(token, USER_TOKEN_SECRET_KEY, (err, payload) => {
            if (err) {
              throw err;
            } else {
              ctx.state.user = payload;
            }
          });
          await next();
        } catch (err) {
          rsp_no_auth("令牌验证失败 请重新登陆");
        }
      }
    }

    function rsp_no_auth(msg) {
      ctx.status = 401;
      ctx.body = { ok: 0, err: msg };
    }
  },
};
